package cn.rocksolid.sport.common.http;

import cn.rocksolid.sport.common.C;
import cn.rocksolid.sport.common.Constant.AppType;
import cn.rocksolid.sport.common.context.RockSolidContextHolder;
import cn.rocksolid.sport.common.context.RockSolidContextImpl;
import cn.rocksolid.sport.common.http.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * RockSolid context filter based on shiro framework
 *
 * @author Axl Zhao
 * @email axl.zhao@163.com
 */
public class RockSolidContextFilter implements Filter {

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
          throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    RockSolidContextImpl temporaryContext = new RockSolidContextImpl();
    temporaryContext.setAgencyId(HttpUtils.retrieveProp(httpRequest, C.AGENCY_ID.p));
    temporaryContext.setAppId(HttpUtils.retrieveProp(httpRequest, C.APP_ID.p));
    String appType = HttpUtils.retrieveProp(httpRequest, C.APP_TYPE.p);
    if (StringUtils.isNotBlank(appType)) {
      temporaryContext.setAppType(AppType.valueOf(appType));
    }
    temporaryContext.setToken(HttpUtils.retrieveProp(httpRequest, C.TOKEN.p));
    temporaryContext.setAccessType(HttpUtils.retrieveAccessType(httpRequest));
    temporaryContext.setClientIp(HttpUtils.retrieveIpAddress(httpRequest));
    RockSolidContextHolder.setContext(temporaryContext);
    chain.doFilter(request, response);
  }
}
